
import React, { FC, useEffect, useRef, useState } from 'react'
import { Button, Form, Input,Toast } from 'antd-mobile'
import { FormItem } from 'antd-mobile/es/components/form/form-item'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { reg } from '../../utils/validate'
import { Http } from '../../api'
import route from '../Search/route'
import { connect } from 'react-redux'
import { getuserInfoAsync } from '../../redux/actions'
const LoginByName:FC<any> = ({
  dispatch
}) => {
  const formRef: any = useRef()
  const [form] = Form.useForm()
  // const [dispatch,setDisabled]= useState<boolean>(true)
  const [searchParams] = useSearchParams()    // 获取query值  
  const router=useNavigate()

  useEffect(()=>{
    console.log(searchParams.get('phone'));  //获取里面phone的值
    const username = searchParams.get('username')
    if (username) {  //取值
      form.setFieldsValue({'username':username}) //设置表单的某个值 //获取值  
    }else{
      form.setFieldsValue({'username':localStorage.getItem('username')})
    }
  },[])

  // 校验成功
  // 注意 异步数据不能解构
  const onFinish=async (value:any)=>{
    let res:any = await Http.login(value)
    if (res.code==200) {
      sessionStorage.setItem("token",res.token) //把用户信息存起来
      localStorage.setItem("username",value.username)
      // dispatch(getuserInfoAsync()) //登录成功 发送 getuserInfoAsync

       // 解决异步问题 当数据请求成功后，再向下执行后面的操作（同步）
      let data:any = await Http.getuserinfo({})
      if (data.code==200) {
        ({
          type:"getuserInfoAsync",
          payload:data.result
        })
      }
      // 需要继续优化
      if (searchParams.get('from')) {
        // good
        router('/main/mine')
      }else{
      router(-1)  //回退上一级
    }
    }
  
    
  }

  // const onFinish=async (value:any)=>{
  //   console.log(value);
  //   console.log(form.getFieldsValue());  //获取（拿到里面的值）
  //   let res:any = await Http.register(value)
  //   if (res.code==200) {
  //     router('/login?'+qs.stringify(value))
  //   }
    
  // }

  // 校验失败
  const onFinishFailed=()=>{
    Toast.show({
      content: '请输入有效的登录信息',
    })
  }
  return (
    <div>
      
      <Form 
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      ref={formRef}
      form={form}
      layout='horizontal' mode='card'
        footer={
          <div style={{width:'100%',display:'flex'}}>
            <Button style={{flex:1,margin:'0 10px'}} type='submit' color='success' size='large'>
              登录
            </Button>
            <Button
           style={{flex:1,margin:'0 10px'}}
              color='danger'
              onClick={() => {
                formRef.current.resetFields()
              }}
              size='large'
            >重置</Button>
            
          </div>
        }
      >
        <Form.Item label='用户名' name='username'
         rules={[
          { required: true },
        ]}
        >
          <Input placeholder='请输入用户名' clearable />
        </Form.Item>
        <Form.Item label='密码' name='password'
         rules={[
          { required: true },
          {pattern:reg.pwd,message:"请输入6-16位的字母和数字组合的密码"}
        ]}
        >
          <Input placeholder='请输入密码' clearable type='password' />
        </Form.Item>
      
        <Form.Item>
          <div className="lines" style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <div className="item">
            <Link to="/register" style={{color:'pink'}}>去注册?</Link>
            </div>
            <div className="item">
            <Link to="/findpass" style={{color:'#f50'}}>找回密码?</Link>
            </div>
          </div>
        </Form.Item>
      </Form>
    </div>
  )
}

export default connect()(LoginByName)